Dynamic memory allocation in C allows allocating memory for variables at runtime, rather than at compile time. This is achieved using four library functions: malloc, calloc, realloc, and free, which are defined in the stdlib.h header file.
malloc: Allocates a block of memory of a specified size and returns a pointer to the first byte of the allocated memory.
calloc: Allocates memory for an array of elements of a specified size and initializes all bytes to zero.
realloc: Changes the size of the previously allocated memory block.
free: Frees the memory previously allocated by malloc, calloc, or realloc, releasing it back to the system.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Dynamic memory allocation for an array of integers
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int *dynamicArray = (int *)malloc(size * sizeof(int));
// Check if memory allocation was successful
if (dynamicArray == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input array elements
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &dynamicArray[i]);
}
// Output array elements
printf("Array Elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", dynamicArray[i]);
}
printf("\n");
// Free the allocated memory
free(dynamicArray);
return 0;
}
Enter the size of the array: 5
Enter 5 elements:
10 20 30 40 50
Array Elements: 10 20 30 40 50
What is malloc used for in C?
What does calloc initialize memory to in C?
What is the purpose of realloc in C?
What function is used to release memory in C?
What is the return type of malloc in C?